from django.dispatch import receiver
from django.db.models.signals import post_save, pre_save

from .models import ConsumeRecord, ServeGift, EnterStoreRecord


@receiver(post_save, sender=ConsumeRecord)
def decrease_gift_count(sender, instance=None, created=None, *args, **kwargs):
    if created:
        instance.gift.count -= instance.count
        instance.gift.save()


@receiver(post_save, sender=ServeGift, dispatch_uid="new_enter_store_record")
def new_enter_store_record(sender, instance=None, created=None, *args, **kwargs):
    if created:
        EnterStoreRecord.objects.create(gift=instance, count=instance.count)


@receiver(pre_save, sender=ServeGift, dispatch_uid="update_enter_store_record")
def update_enter_store_record(sender, instance=None, *args, **kwargs):
    try:
        old_instance = ServeGift.objects.get(id=instance.id)
    except ServeGift.DoesNotExist:
        pass
    else:
        count = instance.count - old_instance.count
        if count > 0:
            EnterStoreRecord.objects.create(gift=instance, count=count)
